package com.example.tool.activtiy;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.alibaba.fastjson.JSON;
import com.example.tool.R;
import com.example.tool.activtiy.base.BaseActivity;
import com.example.tool.mvp.CommonPresent;
import com.example.tool.util.CalendarUtil;
import com.example.tool.util.DebugLog;
import com.example.tool.util.FileUtil;
import com.example.tool.util.GsonUtil;
import com.example.tool.util.net.BaiduUtil;
import com.example.tool.util.net.Base64Util;
import com.example.tool.util.net.FigureResponceBean;
import com.example.tool.util.net.FigureSendBean;
import com.example.tool.util.net.HttpUtil;
import com.example.tool.util.net.RetrofitUtil;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.RequestBody;
import rx.Observer;

import static com.example.tool.util.DebugLog.KUN;

/**
 * https://github.com/aserbao/AndroidCamera
 */
public class TikAiActivity extends BaseActivity<CommonPresent> {

//    @BindView(R.id.iv_matrix)
//    ImageView iv_splash;

    @BindView(R.id.btn_figure)
    Button btnFigure;

    private static final String APP_ID = "19618013";
    private static final String API_KEY = "5DN0AGilS6YkGjUD1SRbeU8M";
    private static final String SECRET_KEY = "uHvugCwkDXQyHi5Kqn9zh4bnLb9gKWcM";
    private String access_token;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_tiktok;
    }

    @Override
    protected void initView() {


    }


    @Override
    protected void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    access_token = BaiduUtil.getAuth(API_KEY, SECRET_KEY);

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();


    }

    private FigureSendBean getSendBean() {
        FigureSendBean sendBean = new FigureSendBean();
        sendBean.setAppid(APP_ID);
        sendBean.setMusic_id(1);
        sendBean.setFps(20);
        sendBean.setMorph_time(1f);
        sendBean.setOutput_width(800);
        sendBean.setOutput_height(1280);
        sendBean.setOutput_type("GIF");
        List<FigureSendBean.ImageBean> stringList = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            String image = "";
            Bitmap bitmap = null;

            FigureSendBean.ImageBean imageBean = null;
            String sdcardPath = FileUtil.getInstance().getSdcardPath() + File.separator + "DCIM/Camera";
            switch (i) {
                case 0:
//                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kun01);
                    String path01 = sdcardPath + File.separator + "kun01.jpg";
                    image = picToBase64(path01);
                    imageBean = new FigureSendBean.ImageBean();
                    imageBean.setImage(image);
                    DebugLog.d(DebugLog.KUN + "image 01 " + image);
                    break;
                case 1:
//                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kun02);
                    String path02 = sdcardPath + File.separator + "kun02.jpg";
                    image = picToBase64(path02);
                    imageBean = new FigureSendBean.ImageBean();
                    imageBean.setImage(image);
                    DebugLog.d(DebugLog.KUN + "image 02 " + image);
                    break;
                case 2:
//                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kun03);
                    String path03 = sdcardPath + File.separator + "kun03.jpg";
                    image = picToBase64(path03);
                    imageBean = new FigureSendBean.ImageBean();
                    imageBean.setImage(image);
                    DebugLog.d(DebugLog.KUN + "image 03 " + image);
                    break;
                case 3:
//                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kun04);
                    String path04 = sdcardPath + File.separator + "kun04.jpg";
                    image = picToBase64(path04);
                    imageBean = new FigureSendBean.ImageBean();
                    imageBean.setImage(image);
                    DebugLog.d(DebugLog.KUN + "image 04 " + image);
                    break;
//                case 4:
////                    bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.kun05);
////                    image = picToBase64(bitmap);
//
//                    String path05 = sdcardPath + File.separator + "kun05.jpg";
//                    image = picToBase64(path05);
//                    imageBean = new FigureSendBean.ImageBean();
//                    imageBean.setImage(image);
//                    DebugLog.d(DebugLog.KUN + "image 05 " + image);
//                    break;

            }
            if (!TextUtils.isEmpty(image)) {
                stringList.add(imageBean);
            }
        }

        sendBean.setImage_list(stringList);
        //每张图片的展示时长, 以空格分隔 数量要求和请求的图片张数一致 GIF默认每张图片0.7s 视频默认每张图片2s
//        //这个参数必须给 且和 图片个数一致  用空格 隔开
        sendBean.setTempo("3 3 3 3");
        return sendBean;
    }

    @Override
    protected void initEvent() {
//        String BASE_BAIDU = "https://aip.baidubce.com/rest/2.0/face/v1/gradient";
//        String BASE_BAIDU = "https://aip.baidubce.com/rest/2.0/face/v1/";

        String BASE_BAIDU = "https://aip.baidubce.com/rest/2.0/face/v1/gradient";
        btnFigure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(() -> {
//                    https://aip.baidubce.com/rest/2.0/face/v1/gradient?access_token=你的access_token的值
                    FigureSendBean sendBean = getSendBean();


                    long startTime = CalendarUtil.getCurrentTimeMillis();

                    String param = JSON.toJSONString(sendBean);

                    try {
                        String result = HttpUtil.post(BASE_BAIDU, access_token, param);


                        DebugLog.d(DebugLog.KUN + "result " + result);

                        FigureResponceBean responseBean = JSON.parseObject(result, FigureResponceBean.class);
                        if (responseBean.getError_code() == 0) {
                            long endTime = CalendarUtil.getCurrentTimeMillis();
                            DebugLog.d(KUN + "上传请求回来的耗时 " + (endTime - startTime) / 1000 + " 秒");
                            Base64Util.GenerateBase64ToFile(responseBean.getResult().getOutput(), sendBean.getOutput_type());
                            long endTime2 = CalendarUtil.getCurrentTimeMillis();
                            DebugLog.d(KUN + "转换视频耗时 " + (endTime2 - endTime) / 1000 + " 秒");
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

//                    String json = GsonUtil.toJson(sendBean);
//                    RequestBody requestBody = GsonUtil.getRequestBodyCommon(json);
//                    RetrofitUtil.getInstance().request(BASE_BAIDU). apiService.sendToWeb(access_token, requestBody)
//                    RetrofitUtil.getInstance().request(BASE_BAIDU).apiService.sendToWeb(access_token,sendBean)
//                            .subscribe(new Observer<FigureResponceBean>() {
//                                @Override
//                                public void onCompleted() {
//
//                                }
//
//                                @Override
//                                public void onError(Throwable e) {
//                                    DebugLog.d(KUN + "BindNAS Other " + e.toString());
//
//                                }
//
//                                @Override
//                                public void onNext(FigureResponceBean bean) {
//
//                                    DebugLog.d(KUN + "bean " + bean.toString());
//                                }
//
//                            });
                }).start();

            }
        });


    }

    @Override
    protected CommonPresent createPresenter() {
        return null;
    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//
//
//    }

    /**
     * 图片转为64位流
     *
     * @return
     */
    public String picToBase64(String path) {
        String encode = "";
        try {
            encode = Base64Util.encode(FileUtil.readFileByBytes(path));
//            encode = Base64Util.encode(Bitmap2Bytes(bm));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return encode;
    }

    /**
     * 把Bitmap转Byte
     */
    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

}
